package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.smart.village.big.screen.domain.SendMessage;
import com.smart.village.big.screen.mapper.GridInformationMapper;
import com.smart.village.big.screen.mapper.PartyOrganizationActivityMapper;
import com.smart.village.big.screen.service.WxMPService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.swing.text.DateFormatter;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

@Service
public class WxMPServiceImpl implements WxMPService {
    java.util.logging.Logger logger = Logger.getLogger(WxMPServiceImpl.class.getName());
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Value("${wx.mp.appId}")
    private String appId;

    @Value("${wx.mp.appSecret}")
    private String appSecret;

    @Value("${wx.miniprogram.appId}")
    private String miniprogramAppId;

    @Autowired
    private PartyOrganizationActivityMapper partyOrganizationActivityMapper;

    @Autowired
    private GridInformationMapper gridInformationMapper;

    @Override
    public JSONObject sendTemplateMessage(SendMessage sendMessage) {
        HttpClient client = HttpClient.newHttpClient();
        logger.info("sendTemplateMessage, sendMessage: {}" + sendMessage.toString());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", sendMessage.getOpenId());
        jsonObject.put("template_id", sendMessage.getTemplateId());
        jsonObject.put("data", sendMessage.getContent());
        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid", miniprogramAppId);
        miniprogram.put("page", "pages/initial/index");
        jsonObject.put("miniprogram", miniprogram);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getToken()))
                .POST(HttpRequest.BodyPublishers.ofString(jsonObject.toJSONString()))
                .build();

        HttpResponse<String> response = null;
        try {
            response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (java.io.IOException | InterruptedException e) {
            e.printStackTrace();
        }
        if (response != null) {
            logger.info("sendTemplateMessage, response: {}" + response.body());
        }
        if (response != null) {
            return JSONObject.parseObject(response.body());
        }
        return null;
    }

    @Override
    public JSONObject sendMicroProgramTemplateMessage(SendMessage sendMessage) {
        HttpClient client = HttpClient.newHttpClient();
        logger.info("sendMicroProgramTemplateMessage, sendMessage: {}" + sendMessage.toString());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", sendMessage.getOpenId());
        jsonObject.put("template_id", sendMessage.getTemplateId());
        jsonObject.put("data", sendMessage.getContent());
        JSONObject miniprogram = new JSONObject();
        miniprogram.put("appid", miniprogramAppId);
        miniprogram.put("page", "pages/initial/index");
        jsonObject.put("miniprogram", miniprogram);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getMicroProgramToken(miniprogramAppId)))
                .POST(HttpRequest.BodyPublishers.ofString(jsonObject.toJSONString()))
                .build();

        HttpResponse<String> response = null;
        try {
            response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (java.io.IOException | InterruptedException e) {
            e.printStackTrace();
        }
        if (response != null) {
            logger.info("sendMicroProgramTemplateMessage, response: {}" + response.body());
        }
        if (response != null) {
            return JSONObject.parseObject(response.body());
        }
        return null;
    }

    private String getMicroProgramToken(String miniprogramAppId) {
        return partyOrganizationActivityMapper.getMicroProgramToken(miniprogramAppId).getString("Access_Token");
    }

    @Override
    public JSONObject sendActivityMessage(String member, String data) {
        int cnt = 0;
        SendMessage sendMessage = new SendMessage();
        List<String> errorList = Lists.newArrayList();
        //todo 做数据库配置
        sendMessage.setTemplateId("8QQtvu8V5EeHd3eK2laKfjMjSo3inD5cEUwqF-dXMJw");

        if (StringUtils.isNotBlank(data) && !ObjectUtils.isEmpty(data)) {

            // 活动消息
            List<JSONObject> dataList = partyOrganizationActivityMapper.getSendActivityMessageData(data, member);
            if (dataList != null && dataList.size() > 0) {
                sendMessage.setOpenId(dataList.get(0).getString("Open_ID"));

                JSONObject partyOrganizationActivity = partyOrganizationActivityMapper.selectPartyOrganizationActivityByPrimaryKey(data);
                if (partyOrganizationActivity != null) {
                    String Activity_Name = partyOrganizationActivity.getString("Activity_Name");
                    String Activity_Content = partyOrganizationActivity.getString("Activity_Content");
                    JSONObject JSONObject_Data = new JSONObject();

                    JSONObject JSONObject_firstDATA = new JSONObject();
                    JSONObject_firstDATA.put("value", "党员大会活动");
                    JSONObject_Data.put("first", JSONObject_firstDATA);

                    JSONObject JSONObject_keyword1DATA = new JSONObject();
                    JSONObject_keyword1DATA.put("value", Activity_Name);
                    JSONObject_Data.put("keyword1", JSONObject_keyword1DATA);

                    JSONObject JSONObject_keyword2DATA = new JSONObject();
                    JSONObject_keyword2DATA.put("value", Activity_Content);
                    JSONObject_Data.put("keyword2", JSONObject_keyword2DATA);

                    JSONObject JSONObject_remarkDATA = new JSONObject();
                    JSONObject_remarkDATA.put("value", "1");
                    JSONObject_Data.put("remark", JSONObject_remarkDATA);

                    sendMessage.setContent(JSONObject_Data);
                }
                JSONObject sendResult = sendTemplateMessage(sendMessage);
                System.out.println(sendResult.toJSONString());
                if (sendResult != null && sendResult.getString("errmsg").equals("ok")) {
                    cnt++;
                } else {
                    errorList.add(dataList.get(0).getString("Personal_Name"));
                }
            }
        }

        return JSONObject.parseObject("{\"successCnt\":\"" + cnt + "\",\"unsubscribed\":" + JSONArray.toJSONString(errorList) + "}");

    }

     @Override
    public JSONObject sendPartyFeeMessage(String data, String msg) {
        int cnt = 0;
        List<String> errorList = Lists.newArrayList();
        SendMessage sendMessage = new SendMessage();
        //todo 做数据库配置
        sendMessage.setTemplateId("nQ8botlRyqIgjyeitjtaI3eN_Hz423mlzCq8RvSxeko");

        if (StringUtils.isNotBlank(data) && !ObjectUtils.isEmpty(data)) {

            String[] split = data.split(",");
            for (String s : split) {
                JSONObject memberInfo = partyOrganizationActivityMapper.getSendPartyFeeMessageMemberInfo(s);
                if (memberInfo != null) {
                    if (StringUtils.isNotBlank(memberInfo.getString("Open_ID"))) {
                        sendMessage.setOpenId(memberInfo.getString("Open_ID"));
                        String Arg_Content = "您的党费暂未缴纳，请及时缴纳";
                        if (StringUtils.isNotBlank(msg)) {
                            Arg_Content = msg;
                        }
                        JSONObject JSONObject_Data = new JSONObject();

                        JSONObject JSONObject_thing1DATA = new JSONObject();
                        JSONObject_thing1DATA.put("value", "党费缴纳通知");
                        JSONObject_Data.put("thing1", JSONObject_thing1DATA);

                        JSONObject JSONObject_thing3DATA = new JSONObject();
                        JSONObject_thing3DATA.put("value", "待缴费");
                        JSONObject_Data.put("thing3", JSONObject_thing3DATA);

                        JSONObject JSONObject_thing5DATA = new JSONObject();
                        JSONObject_thing5DATA.put("value", Arg_Content);
                        JSONObject_Data.put("thing5", JSONObject_thing5DATA);

                        sendMessage.setContent(JSONObject_Data);
                        JSONObject sendResult = sendMicroProgramTemplateMessage(sendMessage);
                        System.out.println(sendResult.toJSONString());

                        if (sendResult != null && sendResult.get("errmsg").equals("ok")) {
                            cnt++;
                        } else {
                            errorList.add(memberInfo.getString("Personal_Name"));
                        }
                    } else {
                        errorList.add(memberInfo.getString("Personal_Name"));
                    }
                }
            }
        }
        return JSONObject.parseObject("{\"successCnt\":\"" + cnt + "\",\"unsubscribed\":" + JSONArray.toJSONString(errorList) + "}");
    }

    @Override
    public JSONObject sendComplaintsMessage(String data) {
        int cnt = 0;
        List<String> errorList = Lists.newArrayList();
        SendMessage sendMessage = new SendMessage();
        //todo 做数据库配置
        sendMessage.setTemplateId("4PbnStNuKulqdX2DHrXyTmRfim9aI60bZhj61juhvpY");

        if (StringUtils.isNotBlank(data) && !ObjectUtils.isEmpty(data)) {

            String[] split = data.split(",");
            for (String s : split) {
                JSONObject dataInfo = partyOrganizationActivityMapper.getSendComplaintsMessage(s);
                if (dataInfo != null) {
                    if (StringUtils.isNotBlank(dataInfo.getString("OpenID"))) {
                        sendMessage.setOpenId(dataInfo.getString("OpenID"));
                        JSONObject JSONObject_Data = new JSONObject();

                        JSONObject JSONObject_thing1DATA = new JSONObject();
                        JSONObject_thing1DATA.put("value", dataInfo.getString("title"));
                        JSONObject_Data.put("thing1", JSONObject_thing1DATA);

                        JSONObject JSONObject_thing3DATA = new JSONObject();
                        JSONObject_thing3DATA.put("value", dataInfo.getString("content"));
                        JSONObject_Data.put("thing4", JSONObject_thing3DATA);

                        JSONObject JSONObject_thing5DATA = new JSONObject();
                        JSONObject_thing5DATA.put("value", dataInfo.getString("Operation_Datetime"));
                        JSONObject_Data.put("date3", JSONObject_thing5DATA);

                        sendMessage.setContent(JSONObject_Data);
                        JSONObject sendResult = sendMicroProgramTemplateMessage(sendMessage);
                        System.out.println(sendResult.toJSONString());

                        if (sendResult != null && sendResult.get("errmsg").equals("ok")) {
                            cnt++;
                        } else {
                            errorList.add(dataInfo.getString("Personal_Name"));
                        }
                    } else {
                        errorList.add(dataInfo.getString("Personal_Name"));
                    }
                }
            }
        }
        return JSONObject.parseObject("{\"successCnt\":\"" + cnt + "\",\"unsubscribed\":" + JSONArray.toJSONString(errorList) + "}");
    }

    @Override
    public JSONObject sendGridTaskMessage() {
        int cnt = 0;
        List<String> errorList = Lists.newArrayList();
        SendMessage sendMessage = new SendMessage();
        //todo 做数据库配置
        sendMessage.setTemplateId("tP5n7jHkEiY-ay0kEBmn14wQNEnmNRUenefcMlKGE3s");

        List<JSONObject> dataInfoList = gridInformationMapper.sendGridTaskMessage();
        if (!CollectionUtils.isEmpty(dataInfoList)) {
            for (JSONObject dataInfo : dataInfoList) {
                if (StringUtils.isNotBlank(dataInfo.getString("OpenID"))) {
                    sendMessage.setOpenId(dataInfo.getString("OpenID"));
                    JSONObject JSONObject_Data = new JSONObject();

                    JSONObject JSONObject_thing1DATA = new JSONObject();
                    JSONObject_thing1DATA.put("value", dataInfo.getString("Personal_Name"));
                    JSONObject_Data.put("name1", JSONObject_thing1DATA);

                    JSONObject JSONObject_thing2DATA = new JSONObject();
                    JSONObject_thing2DATA.put("value", "【网格巡逻任务】"+dataInfo.getString("Task_Name"));
                    JSONObject_Data.put("thing2", JSONObject_thing2DATA);

                    JSONObject JSONObject_thing3DATA = new JSONObject();
                    JSONObject_thing3DATA.put("value", dataInfo.getString("Done_Cnt") + "/" + dataInfo.getString("Plan_Cnt"));
                    JSONObject_Data.put("thing3", JSONObject_thing3DATA);

                    JSONObject JSONObject_thing4DATA = new JSONObject();
                    String createDatetime1 = dataInfo.getString("Create_Datetime");
                    if(createDatetime1.length()>19){
                        createDatetime1 = createDatetime1.substring(0,19);
                    }
                    JSONObject_thing4DATA.put("value",  createDatetime1);
                    JSONObject_Data.put("date7", JSONObject_thing4DATA);

                    JSONObject JSONObject_thing5DATA = new JSONObject();
                    JSONObject_thing5DATA.put("value", dataInfo.getString("grid_name"));
                    JSONObject_Data.put("thing9", JSONObject_thing5DATA);


                    sendMessage.setContent(JSONObject_Data);
                    JSONObject sendResult = sendMicroProgramTemplateMessage(sendMessage);
                    System.out.println(sendResult.toJSONString());

                    if (sendResult != null && sendResult.get("errmsg").equals("ok")) {
                        cnt++;
                    } else {
                        errorList.add(dataInfo.getString("Personal_Name"));
                    }
                }
            }

        }

        return JSONObject.parseObject("{\"successCnt\":\"" + cnt + "\",\"unsubscribed\":" + JSONArray.toJSONString(errorList) + "}");
    }

    @Override
    public JSONObject sendPatrolTaskMessage() {
        int cnt = 0;
        List<String> errorList = Lists.newArrayList();
        SendMessage sendMessage = new SendMessage();
        //todo 做数据库配置
        sendMessage.setTemplateId("tP5n7jHkEiY-ay0kEBmn14wQNEnmNRUenefcMlKGE3s");

        List<JSONObject> dataInfoList = gridInformationMapper.sendPatrolTaskMessage();
        if (!CollectionUtils.isEmpty(dataInfoList)) {
            for (JSONObject dataInfo : dataInfoList) {
                if (StringUtils.isNotBlank(dataInfo.getString("OpenID"))) {
                    sendMessage.setOpenId(dataInfo.getString("OpenID"));
                    JSONObject JSONObject_Data = new JSONObject();

                    JSONObject JSONObject_thing1DATA = new JSONObject();
                    JSONObject_thing1DATA.put("value", dataInfo.getString("Personal_Name"));
                    JSONObject_Data.put("name1", JSONObject_thing1DATA);

                    JSONObject JSONObject_thing2DATA = new JSONObject();
                    JSONObject_thing2DATA.put("value", "【巡边任务】"+dataInfo.getString("Task_Name"));
                    JSONObject_Data.put("thing2", JSONObject_thing2DATA);

                    JSONObject JSONObject_thing3DATA = new JSONObject();
                    JSONObject_thing3DATA.put("value", dataInfo.getString("Task_Status"));
                    JSONObject_Data.put("thing3", JSONObject_thing3DATA);

                    JSONObject JSONObject_thing4DATA = new JSONObject();
                    String createDatetime1 = dataInfo.getString("PlanDate");
                    if(createDatetime1.length()>19){
                        createDatetime1 = createDatetime1.substring(0,19);
                    }
                    JSONObject_thing4DATA.put("value",  createDatetime1);
                    JSONObject_Data.put("date7", JSONObject_thing4DATA);

                    JSONObject JSONObject_thing5DATA = new JSONObject();
                    JSONObject_thing5DATA.put("value", dataInfo.getString("Task_Area"));
                    JSONObject_Data.put("thing9", JSONObject_thing5DATA);


                    sendMessage.setContent(JSONObject_Data);
                    JSONObject sendResult = sendMicroProgramTemplateMessage(sendMessage);
                    System.out.println(sendResult.toJSONString());

                    if (sendResult != null && sendResult.get("errmsg").equals("ok")) {
                        cnt++;
                    } else {
                        errorList.add(dataInfo.getString("Personal_Name"));
                    }
                }
            }

        }

        return JSONObject.parseObject("{\"successCnt\":\"" + cnt + "\",\"unsubscribed\":" + JSONArray.toJSONString(errorList) + "}");
    }

    @Override
    public JSONObject sendHelpMessage(String data) {
        int cnt = 0;
        List<String> errorList = Lists.newArrayList();
        SendMessage sendMessage = new SendMessage();
        //todo 做数据库配置
        sendMessage.setTemplateId("tP5n7jHkEiY-ay0kEBmn14wQNEnmNRUenefcMlKGE3s");

        List<JSONObject> dataInfoList = gridInformationMapper.sendHelpMessage(data);
        if (!CollectionUtils.isEmpty(dataInfoList)) {
            for (JSONObject dataInfo : dataInfoList) {
                if (StringUtils.isNotBlank(dataInfo.getString("OpenID"))) {
                    sendMessage.setOpenId(dataInfo.getString("OpenID"));
                    JSONObject JSONObject_Data = new JSONObject();

                    JSONObject JSONObject_thing1DATA = new JSONObject();
                    JSONObject_thing1DATA.put("value", dataInfo.getString("Name"));
                    JSONObject_Data.put("name1", JSONObject_thing1DATA);

                    JSONObject JSONObject_thing2DATA = new JSONObject();
                    JSONObject_thing2DATA.put("value", "【帮办代办】"+dataInfo.getString("Application_Content"));
                    JSONObject_Data.put("thing2", JSONObject_thing2DATA);

                    JSONObject JSONObject_thing3DATA = new JSONObject();
                    JSONObject_thing3DATA.put("value", "待处理");
                    JSONObject_Data.put("thing3", JSONObject_thing3DATA);

                    JSONObject JSONObject_thing4DATA = new JSONObject();
                    String createDatetime1 = dataInfo.getString("Application_Date");
                    if(createDatetime1.length()>19){
                        createDatetime1 = createDatetime1.substring(0,19);
                    }
                    JSONObject_thing4DATA.put("value",  createDatetime1);
                    JSONObject_Data.put("date7", JSONObject_thing4DATA);

                    JSONObject JSONObject_thing5DATA = new JSONObject();
                    if(StringUtils.isNotBlank(dataInfo.getString("Office_Person"))){
                        JSONObject_thing5DATA.put("value", "办事人："+dataInfo.getString("Office_Person") +" 办事电话："+dataInfo.getString("Office_Contract"));
                        JSONObject_Data.put("thing9", JSONObject_thing5DATA);
                    }else{
                        JSONObject_thing5DATA.put("value", " ");
                        JSONObject_Data.put("thing9", JSONObject_thing5DATA);
                    }


                    sendMessage.setContent(JSONObject_Data);
                    JSONObject sendResult = sendMicroProgramTemplateMessage(sendMessage);
                    System.out.println(sendResult.toJSONString());

                    if (sendResult != null && sendResult.get("errmsg").equals("ok")) {
                        cnt++;
                    } else {
                        errorList.add(dataInfo.getString("Grid_Member_Name"));
                    }
                }
            }

        }

        return JSONObject.parseObject("{\"successCnt\":\"" + cnt + "\",\"unsubscribed\":" + JSONArray.toJSONString(errorList) + "}");
    }

    @Override
    public JSONObject Authorization_Service(String data) throws IOException, InterruptedException {
        JSONObject JSONObject_Result = GetOpenIDByCode(data, appId, appSecret);
        logger.info("Authorization_Service, JSONObject_Result: {"+ JSONObject_Result.toJSONString() +"}");
        JSONObject result = new JSONObject();
        if(JSONObject_Result != null){
            if(JSONObject_Result.containsKey("errcode")) {
                if (!JSONObject_Result.get("errcode").toString().equals("ok")) {
                    result.put("Status", "error");
                    result.put("Result", JSONObject_Result.getString("errmsg"));
                    return result;
                }
            }
            String ls_Open_ID = JSONObject_Result.getString("openid");
            String ls_Union_ID = JSONObject_Result.getString("unionid");
            String ls_Access_Token = JSONObject_Result.getString("access_token");
            String ls_Refresh_Token = JSONObject_Result.getString("refresh_token");
            long li_Expires_DateTime = new Date().getTime() +7000;
            String ls_ID = ls_Open_ID + '_' + appId;
            List<JSONObject> list = gridInformationMapper.getMemberServiceInfo(ls_ID);
            if(CollectionUtils.isEmpty(list)){
             // insert
                JSONObject lJSONObject_Member_Service = new JSONObject();
                lJSONObject_Member_Service.put("ID", ls_ID);
                lJSONObject_Member_Service.put("Union_ID", ls_Union_ID);
                lJSONObject_Member_Service.put("Open_ID", ls_Open_ID);
                lJSONObject_Member_Service.put("App_ID", appId);
                lJSONObject_Member_Service.put("Access_Token", ls_Access_Token);
                lJSONObject_Member_Service.put("Refresh_Token", ls_Refresh_Token);
                lJSONObject_Member_Service.put("Expires_DateTime", li_Expires_DateTime);
                lJSONObject_Member_Service.put("Creater_SerialNumber", "Admin");
                lJSONObject_Member_Service.put("Creation_Datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                lJSONObject_Member_Service.put("Row_Status", "0");
                lJSONObject_Member_Service.put("Operation_ID", "Admin");
                lJSONObject_Member_Service.put("Operation_Datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                gridInformationMapper.insertMemberServiceInfo(lJSONObject_Member_Service);
            }
            result.put("Status", "success");
            result.put("Result", "成功");
        }
        return result;
    }


    private String getToken() {
        // 从缓存中获取token
        String token = redisTemplate.opsForValue().get("wx:mp:token");
        if (StringUtils.isBlank(token)) {
            // 从微信服务器获取token
            token = getTokenFromWxServer();
            // 缓存token
            redisTemplate.opsForValue().set("wx:mp:token", token, 7140, TimeUnit.SECONDS);
        }
        return token;
    }

    private String getTokenFromWxServer() {
        // 从微信服务器获取token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String token = null;
        try {
            token = HttpClient.newHttpClient().send(HttpRequest.newBuilder().uri(URI.create(url)).GET().build(), HttpResponse.BodyHandlers.ofString()).body();
            logger.info("获取到的token：" + token);

            token = JSONObject.parseObject(token).getString("access_token");
        } catch (java.io.IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return token;
    }

    //微信服务号的app id 和密钥
    public JSONObject GetOpenIDByCode(String Arg_Code, String Arg_Appid, String Arg_Secret) throws IOException, InterruptedException {
        String ls_RequestURL = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + Arg_Appid
                + "&secret=" + Arg_Secret
                + "&code=" + Arg_Code
                + "&grant_type=authorization_code";

        //设置请求须要的head参数
        Map<String, String> lMap_HeadParam = new HashMap<String, String>();
        lMap_HeadParam.put("Content-Type", "application/json");

        String ls_RespondResult = HttpClient.newHttpClient().send(HttpRequest.newBuilder().uri(URI.create(ls_RequestURL)).GET().build(), HttpResponse.BodyHandlers.ofString()).body();
        JSONObject lJSONObject_Result = JSONObject.parseObject(ls_RespondResult);

        return lJSONObject_Result;
    }

}
